package com.yxp.offer;

import com.yxp.util.ListNode;

import java.util.Arrays;

/**
 * @author      : yang.xp
 * @date        : 2021/9/4 16:22
 * @description : 剑指 Offer 06. 从尾到头打印链表
 *
 *
 */
public class Problem06 {

    public static void main(String[] args) {
        ListNode head = ListNode.initListNode();
        Problem06 problem06 = new Problem06();
        System.out.println(Arrays.toString(problem06.print(head)));
        int[] ints = problem06.reversePrint(head);
        System.out.println(Arrays.toString(ints));
    }

    // 并没有什么技巧 重新创建一个数组从最后一个元素开始赋值。
    public int[] reversePrint(ListNode head) {
        int count = 0;
        ListNode tempNode = head;
        while (tempNode != null) {
            count++;
            tempNode = tempNode.next;
        }
        int[] arr = new int[count];
        tempNode = head;
        for (int i = count - 1; i >= 0; i--) {
            arr[i] = tempNode.val;
            tempNode = tempNode.next;
        }
        return arr;
    }

    public int[] print(ListNode head) {
        int count = 1;
        ListNode tempNode = head;
        while (tempNode.next != null) {
            count++;
            tempNode = tempNode.next;
        }
        int[] arr = new int[count];
        tempNode = head;
        int i = 0;
        while (tempNode.next != null) {
            arr[i] = tempNode.val;
            tempNode = tempNode.next;
            i++;
        }
        return arr;
    }
}
